<?php
defined('JETEE_PATH') or exit();

/**
 * Jetee模型专用的Dispatcher类
 * 完成URL解析、路由和调度
 * @author    jetee <112738102@qq.com>
 */
class Dispatcher {

	/**
	 * URL映射到控制器
	 * @access public
	 * @return void
	 */
	static public function dispatch() { //先获取所有值 以后再判断安全
		//当前项目地址 如果/bbs
		$url    =   dirname(_PHP_FILE_);
		if($url == '/' || $url == '\\')
			$url    =   '';
		define('PHP_FILE',$url);

		// 开启子域名部署
		if(C('APP_SUB_DOMAIN_DEPLOY')) {
			$rules      = C('APP_SUB_DOMAIN_RULES');
			if(isset($rules[$_SERVER['HTTP_HOST']])) { // 完整域名或者IP配置
				$rule = $rules[$_SERVER['HTTP_HOST']];
			}else{
			   $subDomain  = strtolower(substr($_SERVER['HTTP_HOST'],0,strpos($_SERVER['HTTP_HOST'],'.')));
				define('SUB_DOMAIN',$subDomain); // 二级域名定义
				if($subDomain && isset($rules[$subDomain])) {
					$rule =  $rules[$subDomain];
				}elseif(isset($rules['*'])){ // 泛域名支持
					if('www' != $subDomain && !in_array($subDomain,C('APP_SUB_DOMAIN_DENY'))) {
						$rule =  $rules['*'];
					}
				}                
			}

			if(!empty($rule)) {
				// 子域名部署规则 '子域名'=>array('分组名/[模块名]','var1=a&var2=b');
				$array  =   explode('/',$rule[0]);
				$module =   array_pop($array);
				if(!empty($module)) {
					$_GET[C('VAR_MODULE')]  =   $module;
					$domainModule           =   true;
				}
				if(!empty($array)) {
					$_GET[C('VAR_GROUP')]   =   array_pop($array);
					$domainGroup            =   true;
				}
				if(isset($rule[1])) { // 传入参数
					parse_str($rule[1],$parms);
					$_GET   =  array_merge($_GET,$parms);
				}
			}
		}
		
		// 获取$_SERVER['PATH_INFO']
		if(!isset($_SERVER['PATH_INFO'])) {
			$types   =  explode(',',C('URL_PATHINFO_FETCH'));
			foreach ($types as $type){
				if(0===strpos($type,':')) {// 支持函数判断
					$_SERVER['PATH_INFO'] =   call_user_func(substr($type,1));
					break;
				}elseif(!empty($_SERVER[$type])) {
					$_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type],$_SERVER['SCRIPT_NAME']))?
						substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME']))   :  $_SERVER[$type];//REDIRECT_PATH_INFO
					break;
				}
			}
		}
		//根据$_SERVER['PATH_INFO']=blog/list/act/a/1/b/2解析成$_GET的g  m a等
		$depr = C('URL_PATHINFO_DEPR');
		if(!empty($_SERVER['PATH_INFO'])) { //如 /model/action/id/1/page/2   如果有PATH_INFO  分解成$_GET
			tag('path_info');
			$part =  pathinfo($_SERVER['PATH_INFO']);//blog/list/a.gif=Array ( [dirname] => blog/list [basename] => a.gif [extension] => gif [filename] => a )
			define('__EXT__', isset($part['extension'])?strtolower($part['extension']):'');
			//禁止访问与去掉扩展名
			if(__EXT__){
				if(C('URL_DENY_SUFFIX') && in_array(__EXT__,C('URL_DENY_SUFFIX'))){
					send_http_status(404);
					exit;
				}
				if(C('URL_HTML_SUFFIX')==__EXT__) $_SERVER['PATH_INFO'] = substr($_SERVER['PATH_INFO'],0,strlen($_SERVER['PATH_INFO'])-strlen(__EXT__)-1);
			}
			
			if(trim($_SERVER['PATH_INFO'],'/')!=''){   // 检测路由规则 如果没有则按默认规则调度URL  路由与得出 g m a 解析参数 存入$_GET
				$paths = explode($depr,trim($_SERVER['PATH_INFO'],'/'));
				$var  =  array();//获取分组 模块与action
				if (C('APP_GROUP_LIST') && !isset($_GET[C('VAR_GROUP')])){
					$var[C('VAR_GROUP')] = in_array(strtolower($paths[0]),explode(',',strtolower(C('APP_GROUP_LIST'))))? array_shift($paths) : '';
					if(C('APP_GROUP_DENY') && in_array(strtolower($var[C('VAR_GROUP')]),explode(',',strtolower(C('APP_GROUP_DENY'))))) exit;
				}
				if(!isset($_GET[C('VAR_MODULE')])) $var[C('VAR_MODULE')]  =   array_shift($paths);
				$var[C('VAR_ACTION')]  =   array_shift($paths);
				// 除去分组、模块与action解析成_GET
				preg_replace_callback('@(\w+)\/([^\/]+)@',function($matches)use(&$var){$var[$matches[1]]=strip_tags($matches[2]);}, implode('/',$paths));
				$_GET   =  array_merge($var,$_GET);
			}
			define('__INFO__',$_SERVER['PATH_INFO']);
		}else{
			define('__INFO__','');
		}
		
		
		define('__SELF__',strip_tags($_SERVER['REQUEST_URI']));// URL常量		
		define('__APP__',strip_tags(PHP_FILE));// 当前项目地址

		// 获取分组 模块和操作名称
		if (C('APP_GROUP_LIST')) {
			define('GROUP_NAME', self::getGroup(C('VAR_GROUP')));
			// 分组URL地址
			define('__GROUP__',(!empty($domainGroup) || strtolower(GROUP_NAME) == strtolower(C('DEFAULT_GROUP')) )?__APP__ : __APP__.'/'.(C('URL_CASE_INSENSITIVE') ? strtolower(GROUP_NAME) : GROUP_NAME));
		}
		
		// 定义项目基础加载路径
		if(defined('GROUP_NAME')) {
			C('CACHE_PATH',CACHE_PATH.GROUP_NAME.'/');
			// 普通分组模式
			$config_path    =   CONF_PATH.GROUP_NAME.'/';
			$common_path    =   COMMON_PATH.GROUP_NAME.'/';             
			// 加载分组配置文件
			if(is_file($config_path.'config.php'))
				C(include $config_path.'config.php');
			// 加载分组别名定义
			if(is_file($config_path.'alias.php'))
				Jetee::addMap(include $config_path.'alias.php');
			// 加载分组tags文件定义
			if(is_file($config_path.'tags.php'))
				C('tags', include $config_path.'tags.php');
			// 加载分组函数文件
			if(is_file($common_path.'function.php'))
				include $common_path.'function.php';
		}else{
			C('CACHE_PATH',CACHE_PATH);
		}       
		define('MODULE_NAME',self::getModule(C('VAR_MODULE')));
		define('ACTION_NAME',self::getAction(C('VAR_ACTION')));
		// 当前模块和分组地址
		$moduleName    =   defined('MODULE_ALIAS')?MODULE_ALIAS:MODULE_NAME;
		if(defined('GROUP_NAME')) {
			define('__URL__',!empty($domainModule)?__GROUP__.$depr : __GROUP__.$depr.( C('URL_CASE_INSENSITIVE') ? strtolower($moduleName) : $moduleName ) );
		}else{
			define('__URL__',!empty($domainModule)?__APP__.'/' : __APP__.'/'.( C('URL_CASE_INSENSITIVE') ? strtolower($moduleName) : $moduleName) );
		}
		// 当前操作地址
		define('__ACTION__',__URL__.$depr.ACTION_NAME);

		//保证$_REQUEST正常取值
		$_REQUEST = array_merge($_POST,$_GET);
	}


	/**
	 * 获得实际的模块名称
	 * @access private
	 * @return string
	 */
	static private function getModule($var) {
		$module = !empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE');
		unset($_GET[$var]);
		if(C('URL_CASE_INSENSITIVE')) {
			// URL地址不区分大小写
			// 智能识别方式 index.php/user_type/index/ 识别到 User_typeAction 模块
			//$module = ucfirst(parse_name($module,1));
			$module = ucfirst(strtolower($module));
		}
		return strip_tags($module);
	}

	/**
	 * 获得实际的操作名称
	 * @access private
	 * @return string
	 */
	static private function getAction($var) {
		$action   =!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION');
		unset($_GET[$var]);
		return strip_tags(C('URL_CASE_INSENSITIVE')?strtolower($action):$action);
	}

	/**
	 * 获得实际的分组名称
	 * @access private
	 * @return string
	 */
	static private function getGroup($var) {
		$group   = !empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP');
		unset($_GET[$var]);
		return strip_tags(C('URL_CASE_INSENSITIVE') ?ucfirst(strtolower($group)):$group);
	}

}
